package com.example.demo.config.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.BaseResult;

import lombok.extern.slf4j.Slf4j;

/**
 * 登陆成功时的处理
 * 
 * @author Administrator
 *
 */
@Slf4j
public class CustomSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
			throws IOException, ServletException {

		log.info("请求路径:" + request.getRequestURL() + "" + response.getStatus());
		response.setContentType("application/json;charset=UTF-8"); // 响应类型

		// 返回时，返回用户token
		BaseResult b = new BaseResult(200, "登陆成功",
				SecurityContextHolder.getContext().getAuthentication().getPrincipal());

		// 拼接json串
		String jsonString = JSONObject.toJSONString(b);

		response.getWriter().write(jsonString);
	}
}
